import UIKit
import AFNetworking
class UserAccountViewModel: NSObject {
    
    static let sharedUserAccountViewModel:UserAccountViewModel = UserAccountViewModel()
    //定义用户账户属性
    var useraccount:UserAccount?
   private override init() {
        useraccount = UserAccount.loadUserAccount()
        super.init()
    }
    //用户是否登录
    var userLogin: Bool {
        return useraccount?.access_token != nil
    }
    //计算当前登录用户的token
    var access_token: String? {
        return useraccount?.access_token
    }
    //用户名称的只读属性
    var userName: String? {
        return useraccount?.name
    }
    //用户头像的url
    var headImageURL: NSURL? {
        if let urlString = useraccount?.avatar_large {
            return NSURL(string: urlString)
        }
        return nil
    }
    //MARK:用AFN发起POST的HTTP网络请求用来换取用户的token
    func loadAccessToken(code: String,finished: (isSuccess: Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //以字典的格式传递参数
        let parameters = ["client_id" : client_id , "client_secret" : client_secret , "grant_type" : "authorization_code" , "code" : code , "redirect_uri" : redirect_uri]
        let Manager = AFHTTPSessionManager()
        
        Manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        Manager.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //as? 尝试将Anyobject 转换为 字典类型数据
            guard let dict = result as? [String : AnyObject] else {
                finished(isSuccess: false)
                return
                
            }
            //进行到这里就是转化成功了
            //转换类型之前可以打印出classforcoder 转换类型string之后无法打印出classforcoder
            let useraccount = UserAccount(dict: dict)
            //使用令牌请求用户的信息
            //call to method '' closure requires explicit ......告诉你在闭包中调用方法需要显式
            self.loadUserInfo(useraccount, finished: finished)
            }) { (_, error) -> Void in
                finished(isSuccess: false)
                print(error)
        }
        
    }
    //MARK:使用令牌请求用户的信息
    
    func loadUserInfo(userAccount: UserAccount,finished: (isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token": userAccount.access_token!,"uid": userAccount.uid!]
     
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //print(result)
            //将得到的数据转化为字典类型
            guard let dict = result as? [String : AnyObject] else {
                finished(isSuccess: false)
                return
            }
            
            let name = dict["name"] as! String
            let avatar_large = dict["avatar_large"] as! String
            //完善模型
            //思考:如果不用参数传递  而直接用类创建一个模型来接收赋值的的话  那就是2个对象了  每个对象都被赋值地不完整  所以需要用参数传递
            userAccount.name = name
            userAccount.avatar_large = avatar_large
            
            userAccount.saveAccount()
            //需要给代理对象的用户模型赋值
            self.useraccount = userAccount
            finished(isSuccess: true)
            }) { (_, Error) -> Void in
                finished(isSuccess: false)
                print(Error)
        }
    }
    
}
